<template>
  <!-- edit profile dialog -->
  <v-dialog v-model="isBioDialogOpen" max-width="750px">
    <v-card class="user-edit-info pa-sm-10 pa-3">
      <v-card-title class="text-center text-h5">
        {{ t('message.profile.edit.title') }}
      </v-card-title>
      <v-card-text class="text-center mt-n2">
        {{ t('message.profile.edit.subtitle') }}
      </v-card-text>

      <v-card-text class="mt-5">
        <v-form ref="userInfoForm" v-model="valid">
          <v-row>
            <v-col cols="12" sm="6">
              <v-select
                v-model="userDataLocal.countryName"
                :items="countryOptions"
                item-text="title"
                item-value="country"
                variant="outlined"
                label="Country"
                density="comfortable"
                :rules="[
                  () =>
                    !!userDataLocal.countryName || 'country must be selected',
                ]"
              ></v-select>
            </v-col>
            <v-col cols="12" sm="6">
              <v-select
                v-model="userDataLocal.language"
                :items="languageOptions"
                item-text="title"
                item-value="language"
                variant="outlined"
                label="Language"
                density="comfortable"
              ></v-select>
            </v-col>
            <v-col cols="12" sm="6">
              <v-select
                v-model="userDataLocal.sex"
                :items="sexOptions"
                item-text="title"
                item-value="value"
                variant="outlined"
                density="comfortable"
                label="Sex"
              ></v-select>
            </v-col>
            <v-col cols="12" sm="6">
              <v-text-field
                v-model="userDataLocal.mobile"
                variant="outlined"
                density="comfortable"
                label="Tel"
              ></v-text-field>
            </v-col>
            <v-col cols="12" sm="6">
              <v-text-field
                v-model="userDataLocal.email"
                variant="outlined"
                density="comfortable"
                label="Billing Email"
                :rules="[() => !!userDataLocal.email || 'email is required']"
              ></v-text-field>
            </v-col>
            <v-col cols="12" sm="6">
              <div class="flex flex-row">
                <v-text-field
                  v-model="userDataLocal.code"
                  variant="outlined"
                  density="comfortable"
                  label="Email validate code"
                  class="flex-1"
                  :rules="[
                    () => !!userDataLocal.code || 'validate code is required',
                    () =>
                      (!!userDataLocal.code &&
                        userDataLocal.code.length === 6) ||
                      'validate code must be 6 characters',
                  ]"
                ></v-text-field>
                <v-btn
                  color="white"
                  variant="outlined"
                  class="bg-[#9155fd] ml-3"
                  style="height: 48px; line-height: 48px"
                  @click.stop="getValidateCode()"
                  :disabled="smsSendBtn"
                >
                  {{ (!smsSendBtn && validateCodeTxt) || smsExpireTime + 's' }}
                </v-btn>
              </div>
            </v-col>
            <v-col cols="12" sm="12">
              <!--              mdi-check -->
              <div class="flex flex-row">
                <v-text-field
                  v-model="userDataLocal.shareUrl"
                  variant="outlined"
                  density="comfortable"
                  label="sponsored links"
                  hide-details="auto"
                  :prefix="config.shortUrlPrefix"
                  class="flex-1"
                  @change="isShareUrlAvailable"
                ></v-text-field>
                <v-btn
                  class="border-[#DBDADE] ml-2"
                  variant="outlined"
                  style="height: 48px; line-height: 48px"
                  v-if="userDataLocal.shareUrl !== '' && !isLinkCorrect"
                >
                  <v-icon size="32" color="red">mdi-account-remove</v-icon>
                </v-btn>
              </div>
              <div class="text-[12px] text-[#928D99] mt-2">
                {{ t('message.profile.edit.intro') }}
              </div>
            </v-col>

            <v-col cols="12" class="d-flex justify-center mt-3">
              <v-btn
                class="me-3 bg-[#9155fd] text-white"
                @click.stop="onSubmit"
              >
                {{ t('message.profile.edit.btn.submit') }}
              </v-btn>

              <v-btn variant="outlined" @click.stop="onCancel">
                {{ t('message.profile.edit.btn.cancel') }}
              </v-btn>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { inject, ref, toRefs, watch } from 'vue';
import {
  checkShareUrlApi,
  countryCodeApi,
  getEmailApi,
  updateUserInfoApi,
} from '@/api/system/user';
import type { UserInfo } from '@/types/user';
import Dialog from '@/components/dialog/dialog';
import { languageOptions, resolveLanguage } from '@/utils';

import config from '@/config';
import { useI18n } from 'vue-i18n';

interface UserInfoEditProps {
  isBioDialogOpen: boolean;
  userData: UserInfo;
}

const props = withDefaults(defineProps<UserInfoEditProps>(), {
  isBioDialogOpen: false,
});

const { isBioDialogOpen, userData } = toRefs(props);

const emit = defineEmits<{
  (e: 'update:is-bio-dialog-open', value: boolean): void;
}>();

const userDataLocal = ref<UserInfo>({
  countryName: undefined,
  language: undefined,
  mobile: undefined,
  email: undefined,
  sex: 0,
  code: undefined,
  shareUrl: undefined,
});

const userInfoForm = ref<any>(null);
const countryOptions: any = [];

const sexOptions = [
  { title: 'Not set', value: 0 },
  { title: 'Men', value: 1 },
  { title: 'Women', value: 2 },
];
const valid = ref<boolean>(true);
const isLinkCorrect = ref<boolean>(true);

const validateCodeTxt = ref<string>('send');
let smsSendBtn = ref<boolean>(false);
let smsExpireTime = ref<number>(60);

const emitter = inject('emitter');
const { t } = useI18n();

const getValidateCode = (): void => {
  if (userDataLocal.value.email === null || userDataLocal.value.email === '') {
    Dialog(t('message.profile.edit.validate.email.empty'));
    return;
  } else if (
    userDataLocal.value.countryName === null ||
    userDataLocal.value.countryName === ''
  ) {
    Dialog(t('message.profile.edit.validate.country.empty'));
    return;
  }

  smsSendBtn.value = true;
  const interval = window.setInterval(() => {
    if (smsExpireTime.value-- <= 0) {
      smsExpireTime.value = 60;
      smsSendBtn.value = false;
      clearInterval(interval);
    }
  }, 1000);

  getEmailApi({
    email: userDataLocal.value.email,
  })
    .then(res => {
      console.log('get email validate code res:', res);
    })
    .catch(err => {
      clearInterval(interval);
      smsExpireTime.value = 60;
      smsSendBtn.value = false;
      Dialog(err.message);

      console.log('get tel validate code err:', err);
    });
};

// on form submit
const onSubmit = () => {
  userInfoForm.value.validate().then(res => {
    console.log('valid:', res.valid);
    valid.value = res.valid;
    if (!valid.value) return;
    console.log('update user info before');
    updateUserInfoApi({
      countryCode: resolveCountry(userDataLocal.value.countryName),
      language:
        userDataLocal.value.language !== null
          ? resolveLanguage(userDataLocal.value.language)
          : '',
      mobile: userDataLocal.value.mobile,
      email: userDataLocal.value.email !== '' ? userDataLocal.value.email : '',
      sex: userDataLocal.value.sex,
      code: userDataLocal.value.code,
      shortUrl:
        userDataLocal.value.shareUrl !== '' &&
        userDataLocal.value.shareUrl !== null
          ? config.shortUrlPrefix + userDataLocal.value.shareUrl
          : '',
    })
      .then((res: any) => {
        console.log('updateUserInfoApi:', res);
        userInfoForm.value.resetValidation();
        emit('update:is-bio-dialog-open', false);
        Dialog(t('message.profile.edit.update.success'));
        // 通知父组件的父组件重新拉取用户信息
        // @ts-ignore
        emitter.emit('refreshUser', true);
      })
      .catch((error: any) => {
        console.log('updateUserInfo err:', error);
        Dialog(t('message.profile.edit.update.fail'));
      });
  });
};
const resolveCountry = (country: string | undefined) => {
  console.log('country:', country);
  if (country === undefined) {
    return undefined;
  }
  console.log('enter resolveCountry');
  return countryOptions.find(
    (item: any) =>
      item.country === country ||
      item.title === country ||
      item.title.indexOf(country) != -1
  )?.country;
};

const isShareUrlAvailable = () => {
  if (userDataLocal.value.shareUrl === '') {
    return;
  }
  checkShareUrlApi({
    shortUrl: config.shortUrlPrefix + userDataLocal.value.shareUrl,
  })
    .then((res: any) => {
      console.log('checkShareUrlApi res:', res);
      isLinkCorrect.value = res;
    })
    .catch(err => {
      isLinkCorrect.value = false;
      console.log('checkShareUrlApi err:', err);
      Dialog(err);
    });
};

// const validateTel = (val: string) => {
//   console.log('validate tel:', val)
//
//   var telRules
//   //  手机号码校验规则需要根据不同国家来判断校验
//   switch (val) {
//     case '+91':
//       // 印度
//       telRules = /^[7-9][0-9]{9}$/
//       break
//     case '+62':
//       // 印度尼西亚
//       telRules = /^[2-9]{1}[0-9]+$/
//       break
//     case '+81':
//       // 日本
//       telRules = /^\d{1,4}[ \-]?\d{1,4}[ \-]?\d{4}$/
//       break
//     case '+82':
//       // 韩国
//       telRules = /^0[71](?:\d{8,9})$/
//       break
//     case '+65':
//       // 新加坡
//       telRules = /^[89]\d{7}$/
//       break
//     case '+66':
//       // 泰国
//       telRules = /^\d{10}$/
//       break
//     case '+971':
//       // 沙特
//       telRules = /^5\\d{8}$/
//       break
//     case '+44':
//       // 英国
//       telRules = /^7\d{9}$/
//       break
//     case '+84':
//       // 越南
//       telRules = /(^(3|5|7|8|9))+([0-9]{8})$/
//       break
//     default:
//       // 默认是美国手机号码正则表达式
//       telRules = /^[2-9]\d{2}[2-9](?!11)\d{6}$/
//   }
//
//   if (!telRules.test(val)) {
//     return 'mobile format is wrong'
//   } else {
//     return true
//   }
// }

countryCodeApi().then((res: any) => {
  console.log('countryCodeApi res:', res);
  res.forEach((item: any) => {
    countryOptions.push({
      title: item.countryName,
      country: item.countryCode,
    });
  });
  console.log(countryOptions);
});

const onCancel = () => {
  emit('update:is-bio-dialog-open', false);
};

userDataLocal.value = JSON.parse(JSON.stringify(userData.value));

watch(
  () => isBioDialogOpen.value,
  () => {
    userDataLocal.value = JSON.parse(JSON.stringify(userData.value));
  }
);
</script>
